<?php

namespace App\Blocks;

use App\Models\ActivityAnswer;
use App\Models\ActivityGoods;
use App\Models\ActivityPrizeLog;
use App\Models\ActivityPrizes;
use App\Models\ActivityUser;
use App\Models\WechatOpenplatformToken;
use App\Models\WechatUser;
use DB;

class User
{
    public function saveWechatUser($data){
        $wechatUserModel = new WechatUser();
        $activityUserModel = new ActivityUser();

        $activityUser = DB::table($activityUserModel->getTable() . ' as au')
            ->select(
                'au.id',
                'au.invite_uid',
                'au.popularity',
                'au.tacit',
                'au.used_popularity',
                'au.used_tacit',
                'au.total_popularity',
                'au.total_tacit',
                'au.invite',
                'au.answer_goods_id',
                'wu.headimgurl',
                'wu.openid',
                'wu.nickname'
            )
            ->leftJoin($wechatUserModel->getTable() . ' as wu', 'au.wechat_uid', '=', 'wu.id')
            ->where('wu.openid', $data['openid'])
            ->first();

        $inviteUid = $data['invite_uid'];
        unset($data['invite_uid']);

        try {
            DB::beginTransaction();

            $wechatUser = WechatUser::updateOrCreate(['openid' => $data['openid']],$data);
            if($wechatUser === false){
                \Log::debug('添加微信用户数据失败'.json_encode($data));
                return false;
            }

            //如果用户没有参加活动
            if(empty($activityUser)){
                if(DB::table($activityUserModel->getTable())->insert([
                    'wechat_uid' => $wechatUser->id,
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'invite_uid' => $inviteUid
                ]) === false){
                    DB::rollBack();
                    \Log::debug('添加活动用户数据失败'.json_encode($data));
                    return false;
                }

                //如果有有效的邀请用户数据
                if($inviteUid > 0) {
                    if (DB::table($activityUserModel->getTable())
                        ->where('id', $inviteUid)
                        ->update([
                            'invite' => DB::raw('invite + 1')
                        ]) === false) {
                        DB::rollBack();
                        \Log::debug("更新邀请数量数据失败,invite uid:{$inviteUid}");
                        return false;
                    }
                }
            }

            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            \Log::debug($exception);
            return false;
        }
    }

    public function getActivityUserInfoByOpenid($openid){
        $wechatUserModel = new WechatUser();
        $activityUserModel = new ActivityUser();
        $activityGoodsModel = new ActivityGoods();

        return DB::table($activityUserModel->getTable() . ' as au')
            ->select(
                'au.id',
                'au.invite_uid',
                'au.popularity',
                'au.tacit',
                'au.used_popularity',
                'au.used_tacit',
                'au.total_popularity',
                'au.total_tacit',
                'au.invite',
                'au.answer_goods_id',
                'wu.headimgurl',
                'wu.openid',
                'wu.nickname',
                'ag.title',
                'ag.img_url'
            )
            ->leftJoin($wechatUserModel->getTable() . ' as wu', 'au.wechat_uid', '=', 'wu.id')
            ->leftJoin($activityGoodsModel->getTable() . ' as ag', 'ag.id', '=', 'au.answer_goods_id')
            ->where('wu.openid', $openid)
            ->first();
    }
    public function getActivityUserInfoByUid($uid){
        $wechatUserModel = new WechatUser();
        $activityUserModel = new ActivityUser();
        $activityGoodsModel = new ActivityGoods();
        $openplatformModel = new WechatOpenplatformToken();

        return DB::table($activityUserModel->getTable() . ' as au')
            ->select(
                'au.id',
                'au.invite_uid',
                'au.popularity',
                'au.tacit',
                'au.used_popularity',
                'au.used_tacit',
                'au.total_popularity',
                'au.total_tacit',
                'au.invite',
                'au.answer_goods_id',
                'wu.headimgurl',
                'wu.openid',
                'wu.nickname',
                'ag.title',
                'ag.img_url',
                'wt.appid'
            )
            ->leftJoin($wechatUserModel->getTable() . ' as wu', 'au.wechat_uid', '=', 'wu.id')
            ->leftJoin($activityGoodsModel->getTable() . ' as ag', 'ag.id', '=', 'au.answer_goods_id')
            ->leftJoin($openplatformModel->getTable() .' as wt', 'wt.id', '=', 'wu.wechat_id')
            ->where('au.id', $uid)
            ->first();
    }

    public function answer($makeuId, $askuId, $answer){
        $activityAnswerModel = new ActivityAnswer();
        $activityUserModel = new ActivityUser();

        //如果回答过该用户的问题，就不能再回答了
        if(ActivityAnswer::where('make_uid', $makeuId)
                ->where('ask_uid', $askuId)
                ->count() > 0){
            return -1;
        }

        if($makeuId == $askuId){
            return -2;
        }

        $result = 0;
        if(ActivityUser::where('id', $askuId)
                ->where('answer_goods_id', $answer)
                ->count() === 1){
            $result = 1;
        }

        $saveData = [
            'make_uid' => $makeuId,
            'ask_uid' => $askuId,
            'answer' => $answer,
            'result' => $result,
            'create_time' => date('Y-m-d H:i:s', time())
        ];

        try {
            DB::beginTransaction();

            //保存答案
            if(DB::table($activityAnswerModel->getTable())->insert($saveData) === false){
                DB::rollBack();
                return false;
            }

            if($result === 1){
                //答案正确的时候默契值+1
                if(DB::table($activityUserModel->getTable())
                        ->where('id', $askuId)
                        ->update([
                            'tacit' => DB::raw('tacit + 1'),
                            'total_tacit' => DB::raw('total_tacit + 1')
                        ])
                    === false){
                    DB::rollBack();
                    return false;
                }
            }

            DB::commit();
            return $result;
        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
        }

    }


    public function answerList($askuId){
        $answerModel = new ActivityAnswer();
        $wechatUserModel = new WechatUser();
        $activityGoodsModel = new ActivityGoods();
        $activityUserModel = new ActivityUser();

        return DB::table($answerModel->getTable() . ' as aw')
            ->select(
                'wu.headimgurl',
                'wu.openid',
                'wu.nickname',
                'ag.title',
                'ag.img_url',
                'aw.result'
            )
            ->leftJoin($activityUserModel->getTable() . ' as au', 'aw.make_uid', '=', 'au.id')
            ->leftJoin($wechatUserModel->getTable() . ' as wu', 'wu.id', '=', 'au.wechat_uid')
            ->leftJoin($activityGoodsModel->getTable() . ' as ag', 'ag.id', '=', 'aw.answer')
            ->where('aw.ask_uid', $askuId)
            ->orderBy('aw.create_time', 'desc')
            ->get();
    }

    public function choseGoods($uid, $gid){
        $activityUserModel = new ActivityUser();
        try {
            $user = DB::table($activityUserModel->getTable())
                ->where('id', $uid)
                ->first();

            if(!empty($user->answer_goods_id)){
                return -1;
            }

            DB::beginTransaction();
            if($user->invite_uid > 0) {
                if (
                    DB::table($activityUserModel->getTable())
                        ->where('id', $user->invite_uid)
                        ->update([
                            'popularity' => DB::raw('popularity + 1'),
                            'total_popularity' => DB::raw('total_popularity + 1'),
                        ]) === false
                ) {
                    return false;
                }
            }
            if(
                DB::table($activityUserModel->getTable())
                    ->where('id', $uid)
                    ->whereNull('answer_goods_id')->update([
                        'answer_goods_id' => $gid
                    ]) == false
            ){
                DB::rollBack();
                return false;
            }

            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
        }
    }

    public function inviteList($uid){
        $wechatUserModel = new WechatUser();
        $activityUserModel = new ActivityUser();

        return DB::table($activityUserModel->getTable() . ' as au')
            ->select(
                'au.id',
                'au.invite_uid',
                'au.popularity',
                'au.tacit',
                'au.used_popularity',
                'au.used_tacit',
                'au.total_popularity',
                'au.total_tacit',
                'au.invite',
                'au.answer_goods_id',
                'wu.headimgurl',
                'wu.openid',
                'wu.nickname',
                'au.create_time'
            )
            ->leftJoin($wechatUserModel->getTable() . ' as wu', 'au.wechat_uid', '=', 'wu.id')
            ->where('au.invite_uid', $uid)
            ->whereNotNull('au.answer_goods_id')
            ->get();
    }

    public function prizeLogList($uid){
        $wechatUserModel = new WechatUser();
        $activityUserModel = new ActivityUser();
        $prizeLogModel = new ActivityPrizeLog();

        return DB::table($prizeLogModel->getTable() . ' as pl')
            ->select(
                'pl.id',
                'pl.title',
                'wu.headimgurl',
                'wu.openid',
                'wu.nickname',
                'pl.create_time'
            )
            ->leftJoin($activityUserModel->getTable() . ' as au', 'au.id', '=', 'pl.uid')
            ->leftJoin($wechatUserModel->getTable() . ' as wu', 'au.wechat_uid', '=', 'wu.id')
            ->where('pl.is_prize', 1)
            ->where('pl.uid', $uid)
            ->get();
    }

    public function rankList(){
        $wechatUserModel = new WechatUser();
        $activityUserModel = new ActivityUser();

        return DB::table($activityUserModel->getTable() . ' as au')
            ->select(
                'au.id',
                'au.invite_uid',
                'au.popularity',
                'au.tacit',
                'au.used_popularity',
                'au.used_tacit',
                'au.total_popularity',
                'au.total_tacit',
                'au.invite',
                'au.answer_goods_id',
                'wu.headimgurl',
                'wu.openid',
                'wu.nickname',
                'au.create_time'
            )
            ->leftJoin($wechatUserModel->getTable() . ' as wu', 'au.wechat_uid', '=', 'wu.id')
            ->orderBy('total_tacit', 'desc')
            ->take(100)
            ->get();
    }

    public function prizeLog($type, $uid){
        $activityUserModel = new ActivityUser();
        $prizeLogModel = new ActivityPrizeLog();
        $prizeModel = new ActivityPrizes();

        $prizeId = 0;

        try{
            DB::beginTransaction();

            if($type == 1){
                //小红包
                if(
                    //小红包优先扣除好人缘卡
                    !DB::table($activityUserModel->getTable())->where('popularity', '>=', 6)
                        ->where('id', $uid)
                        ->update([
                            'popularity' => DB::raw('popularity - 6'),
                            'used_popularity' => DB::raw('used_popularity + 6')
                        ])
                ){
                    if(
                        //好人缘卡扣除失败，则扣除默契值
                        !DB::table($activityUserModel->getTable())->where('tacit', '>=', 10)
                            ->where('id', $uid)
                            ->update([
                                'tacit' => DB::raw('tacit - 10'),
                                'used_tacit' => DB::raw('used_tacit + 10')
                            ])
                    ){
                        return -1;
                    }
                }
            }else if($type == 2){
                //大红包
                if(
                    !DB::table($activityUserModel->getTable())->where('tacit', '>=', 20)
                        ->where('id', $uid)
                        ->update([
                            'tacit' => DB::raw('tacit - 20'),
                            'used_tacit' => DB::raw('used_tacit + 20')
                    ])
                ){
                    return -1;
                }
            }

            $isPrize = false;

            //每个人只能抽两次奖
            if(
                DB::table($prizeLogModel->getTable())->where('uid', $uid)
                    ->where('is_prize', 1)
                    ->count() < env('MAX_PRIZE_COUNT')
            ) {
                $prize = ActivityPrizes::where('prize_id', $type)->orderBy('probability', 'asc')->get();

                $rand = rand(0, 101);

                foreach ($prize as $p) {
                    \Log::debug([$p->probability,$rand]);
                    if ($p->probability >= $rand && $p->num > 0) {
                        //中奖了
                        if (
                            !DB::table($prizeLogModel->getTable())->insert([
                                'uid' => $uid,
                                'title' => $p->title,
                                'is_prize' => 1,
                                'create_time' => date('Y-m-d H:i:s', time()),
                                'type' => $type
                            ])
                        ) {
                            DB::rollBack();
                            return false;
                        }

                        if (
                            !DB::table($prizeModel->getTable())
                                ->where('id', $p->id)
                                ->where('num', '>', 0)
                                ->update([
                                    'num' => DB::raw('num - 1')
                                ])
                        ) {
                            DB::rollBack();
                            return false;
                        }
                        $prizeId = $p->id;
                        $isPrize = true;
                        break;
                    }
                }
            }

            if(!$isPrize){
                //中奖了
                if(
                    !DB::table($prizeLogModel->getTable())->insert([
                        'uid' => $uid,
                        'title' => '谢谢参与',
                        'create_time' => date('Y-m-d H:i:s', time()),
                        'type' => $type
                    ])
                ){
                    DB::rollBack();
                    return false;
                }
            }

            DB::commit();
            return $prizeId;
        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
            return false;
        }

    }
}
